<?php
namespace app\admin\controller\extend;
use addons\mplogin\model\Key;
use think\Db;
use app\common\controller\Mpweixin as Mpweixin;
use app\common\controller\Backend;
define("TOKEN", "GKZZD");
class Wechat {

    public $config;
    public $class_obj;
    public $is_check_signature = false;
    public $type;
    public function __construct()
    {
        //获取配置
        $this->config = array('appid'=>'wxf738585fcc896f2f', 'secret'=>'c05f5108483f88538ca1033eee12d0df','type'=>$this->type);
        $echostr = isset($_GET['echostr']) ? $_GET['echostr'] : ''; // 是否来自于微信的服务器配置验证
        if ($echostr) {
            $this->is_check_signature = true;
        }else{
            $this->is_check_signature = false;
            $this->class_obj = new Mpweixin($this->config); //实例化对应的插件
        }
    }

    public function index()
    {
        if ($this->is_check_signature) {
            $this->valid();
        }else{
            return $this->class_obj->responseMsg();
        }
    }

    public function valid()
    {
        $echoStr = $this->checkSignature();
        if($echoStr){
            header('content-type:text');
            exit($echoStr);
        }
    }

    public function checkSignature()
    {
        ob_clean();
        //微信会发送4个参数到我们的服务器后台 签名 时间戳 随机字符串 随机数
        $signature = $_GET['signature']; // 签名
        $timestamp = $_GET['timestamp']; // 时间戳
        $echoStr = $_GET['echostr']; // 随机字符串
        $nonce = $_GET['nonce']; // 随机数
        if ($signature && $timestamp && $echoStr && $nonce) {
            // 微信公众号基本配置中的token
            $token = TOKEN;
            //将token、timestamp、nonce按字典序排序
            $tmpArr = array($token, $timestamp, $nonce);
            sort($tmpArr, SORT_STRING);
            // 将三个参数字符串拼接成一个字符串进行sha1加密
            $tmpStr = implode($tmpArr);
            $tmpStr = sha1($tmpStr);
            // 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
            if($tmpStr == $signature){
                return $echoStr;
            } else {
                return false;
            }
        }
    }

    public function change_menu(){
        exit('非法访问');
    $jsonmenu = '{
      "button":[
      {
            "name":"高考头条",
           "sub_button":[
            {
               "type":"view",
                "name":"专科录取",
                "url":"http://www.fjgkedu.com/Wap/Web/detail/id/169752.html"
            },
            {
                "type":"view",
                "name":"专科录取结果查询",
                "url":"http://gk.eeafj.cn/jsp/result/lqjg/result_enter.jsp"
            },
            {
                "type":"view",
                "name":"录取通知书查询",
                "url":"http://www.ems.com.cn/mailtracking/lu_qu_tong_zhi_shu_cha_xun.html"
            },{
                "type":"view",
                "name":"填报及录取时间表",
                "url":"http://mp.weixin.qq.com/s?__biz=MzAwODMzODEwMA==&mid=2653112802&idx=1&sn=6b7db521f003caa483f73691b2f7493e&chksm=80a78639b7d00f2f267187168b44d1b80d68f8a6b0495d37559005409e4b086d991d45b7c08a&scene=18#wechat_redirect"
            },{
                "type":"view",
                "name":"福建高考信息平台",
                "url":"http://www.fjgkedu.com"
            }]
       },
       {
           "name":"志愿填报",
           "sub_button":[
            {
                "type":"view",
                "name":"福建高考大数据",
                "url":"http://data.fjgkedu.com/large/index/index.html"
            },

            {
                "type":"view",
                "name":"福建招生计划本",
                "url":"http://data.fjgkedu.com/large/info/plan.html?year=2020"
            },
            {
                "type":"view",
                "name":"志愿填报样表下载",
                "url":"http://www.fjgkedu.com/Info/detail/id/166733.html"
            },
            {
                "type":"view",
                "name":"2021新高考交流群",
                "url":"http://qr.zjgkedu.com/?id=MzM0MzgzMTM3MzIz&channel=28264#"
            }]
       },
       {
           "name":"高考直播",
           "sub_button":[
            {
               "type":"view",
                "name":"填报直播指导",
                "url":"https://wx.vzan.com/live/livedetail-1034308135?v=637308659816432862"
            },
            {
               "type":"view",
               "name":"福建专科校推荐",
               "url":"https://mp.weixin.qq.com/mp/homepage?__biz=MzAwODMzODEwMA==&hid=67&sn=7730a19b2455cb96cf894a66df2f843f&scene=18"
            },
            {
                "type":"view",
                "name":"福建本科校推荐",
                "url":"http://mp.weixin.qq.com/mp/homepage?__biz=MzAwODMzODEwMA==&hid=66&sn=ec03305caf1f721c1a60f58424faed92&scene=18#wechat_redirect"
            },
            {
                "type":"view",
                "name":"志愿填报直播",
                "url": "https://wx.vzan.com/live/livedetail-1034308135?shareuid=245220502&ver=637292105185884642&from=groupmessage"
            },
            {
                "type":"view",
                "name":"教授说专业选择",
                "url":"https://wx.vzan.com/live/channelpage-195350?shareuid=245220502&v=1594017001279"
            }]
       }]
    }';
    $access_token=$this->class_obj->access_token;
    $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access_token;
    $result = $this->https_request($url, $jsonmenu);
dump($result);
    }

    function https_request($url,$data = null){

        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);

        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);

        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

        if (!empty($data)){

            curl_setopt($curl, CURLOPT_POST, 1);

            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

        }

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

        $output = curl_exec($curl);

        curl_close($curl);

        return $output;

    }

    public function get_ticket(){ //创建临时二维码
      //  echo "已注释";

        exit('非法访问');
      return $this->class_obj->getEwm(9999,1);
    }

    public function send_mass($title,$url,$wx_time,$wx_zbf,$wx_content,$wx_mark,$type){ //高招群发
        ini_set('max_execution_time', '0');//不超时
        $ACCESS_TOKEN=$this->class_obj->access_token;
        //$template_id = 'krrAF4H5Jt3aqnrnGS9brps3eDn0BUJNn0fJe-KIXgQ';//配置的模板id
        $template_id = 'cr-F4W2LJZmZ53qA1jMaNDuo6a0axmdAg59XrAxKoRI';//配置的模板id
        $send_template_url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $ACCESS_TOKEN;
        $data=  DB::name('gz_shop_wx')->field('open_id')->where("is_del=0  AND type like '%".$type."%'")->group('open_id')->select();
          for($i=0;$i<count($data);$i++){
              $template = array(
                  'touser' => $data[$i]['open_id'],
                  'template_id' => $template_id,
                  'url' => $url,
                  'data' => array(
                      'first' => array('value' => $title, 'color' => "#173177"),
                      'keyword1' => array('value' => $wx_time, 'color' => '#173177'),
                      'keyword2' => array('value' => $wx_zbf, 'color' => '#173177'),
                      'keyword3' => array('value' => $wx_content, 'color' => '#173177'),
                      'remark' => array('value' => $wx_mark, 'color' => '#FF0000'),)
              );

            $res= $this->post_wx($send_template_url,$template);
         }
    }

    public function post_wx($send_template_url,$template){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $send_template_url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($template));
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;
    }
    public function getUserInfo($open_id){
        $data=$this->class_obj->getUserInfo($open_id,$this->class_obj->access_token);
        return $data;
    }
    public function send_msg()
    {
        exit('非法访问');
        $ACCESS_TOKEN=$this->class_obj->access_token;
        $data = DB::name('gz_shop_wx')->field('open_id')->where("is_del=0  AND type like '%1090%'")->group('open_id')->order('id')->limit(1951,2950)->select();
        for ($i = 0; $i < count($data); $i++) {
            $url="https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$ACCESS_TOKEN."&openid=".$data[$i]['open_id']."&lang=zh_CN";
            $res=$this->getJson($url);
            if($res['subscribe']==0){
               $data= DB::name('gz_shop_wx')->where(['open_id'=>$data[$i]['open_id']])->update(['is_del'=>1]);
               dump($data);
            }
        }
    }

    public function getJson($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        return json_decode($output, true);
    }

    public function getOpenId(){
        exit('非法访问');
        ini_set('max_execution_time', '0');//不超时
        $url= "https://api.weixin.qq.com/cgi-bin/user/get?access_token=".$this->class_obj->access_token."&next_openid=osrzTwdMsf0aevWvtS2N2IASffwY";
        $response= $this->getJson($url);
        for ($i=0;$i<count($response['data']['openid']);$i++){

            DB::name('open_id')->insert(['open_id'=>$response['data']['openid'][$i]]);

        }
    }


    public function seng_mes(){ //高招群发
        exit('非法访问');
        ini_set('max_execution_time', '0');//不超时
        $ACCESS_TOKEN=$this->class_obj->access_token;
        $template_id = '9GbvcKl1KrY4zKzCQkOoHHHdkFv4N2Tbi-IBSMO8p3k';//配置的模板id
        $send_template_url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $ACCESS_TOKEN;
        $data=  DB::name('open_id')->field('open_id')->limit(33400,2000)->select();
        for($i=0;$i<count($data);$i++){
            $template = array(
                'touser' => $data[$i]['open_id'],
                'template_id' => $template_id,
                'url' => "https://mp.weixin.qq.com/s/rFyPAY-WwQFGJ8y3SzWgTQ",
                'data' => array(
                    'first' => array('value' => "查分通知！高考成绩已出，点击查分！", 'color' => "#173177"),
                    'keyword1' => array('value' => "7月24日 14:00", 'color' => '#173177'),
                    'keyword2' => array('value' => "点击查看", 'color' => '#173177'),
                    'remark' => array('value' => "每晚20:00，微信群根据考试院录取规则解读“2020年福建高考志愿填报”，请进群准时观看", 'color' => '#FF0000'),)
            );

            $res= $this->post_wx($send_template_url,$template);
//            echo $res;
        }
    }


    public function get_media(){  //上传永久图片素材

        $access_token=$this->class_obj->access_token;
        $file_path = $_SERVER['DOCUMENT_ROOT'] . "/static/images/wx/xk.png";//获取图片的路径，这里一定要是绝对路径才可以
//        dump($_SERVER['DOCUMENT_ROOT']);exit;
        $url = 'https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=' . $access_token . '&type=image';
        if (!file_exists($file_path)) {
            die('图片不存在');
        }
        $post = array("media" => new \CURLFile($file_path));
        dump($this->CURLSend($url, 'post', $post));

    }

    function CURLSend($url, $method = 'get', $data = '') {
        $headers = array('charset=utf-8');
        $ch = curl_init(); //初始化
        // //设置URL和相应的选项
        curl_setopt($ch, CURLOPT_ENCODING, "");
        curl_setopt($ch, CURLOPT_URL, $url); //指定请求的URL
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); //提交方式
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); //不验证SSL
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); //不验证SSL
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); //设置HTTP头字段的数组
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible;MSIE 5.01;Windows NT 5.0)'); //头的字符串
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1); //自动设置header中的Referer:信息
        if ($method == 'post' && !empty($data)) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        } //提交数值
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //是否输出到屏幕上,true不直接输出
        $temp = curl_exec($ch); //执行并获取结果
        curl_close($ch);
        return $temp; //return 返回值json字符串
    }

//    public function get_code(){ //创建临时二维码
//        //  echo "已注释";
//
//        $code=input('post.code');
//        if (empty($code)) return ['status'=>400,'msg'=>'未知错误'];
////        exit('非法访问');
//        return ['status'=>200,'msg'=>'获取成功','code'=>$this->class_obj->getEwm_1($code)];
//
//    }
    public function curlPost($url, $data = null)
    {
        //创建一个新cURL资源
        $curl = curl_init();
        //设置URL和相应的选项
        curl_setopt($curl, CURLOPT_URL, $url);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //执行curl，抓取URL并把它传递给浏览器
        $output = curl_exec($curl);
        //关闭cURL资源，并且释放系统资源
        curl_close($curl);
        return $output;
    }
    public function get_code(){
        $code=input('post.code');
        if (empty($code)){
            $result = ['status'=>400,'msg'=>'未知错误'];
        } else{
//            $ewm=$this->getEwm($code);
            $url='http://admin.gkzzd.cn/dMyrxOzYpf.php/extend/wechat/get_code_api';
            $params = ['code'=>$code];
            $result = $this->curlPost($url,$params);
            $re = json_decode($result,true);
            if($re['status']==200){
                $result = ['status'=>200,'msg'=>'获取成功','ewm'=>$re['code']];
            }else{
                $result = ['status'=>400,'msg'=>'未知错误'];
            }

        }
        echo json_encode($result);
    }


}